let editingId;
let requestUrl;
let data = {};

function addHandler() {
	$("#score").numberspinner("setValue", 0);

	requestUrl = "/qiling/insert";

	$("#qiling_dialog").dialog("open");
}

function editHandler() {
	let rowData = $("#qiling_list").datagrid("getSelected");

	if (rowData) {
		requestUrl = "/qiling/updateById";

		$("#id").val(rowData.id);
		$("#forger").textbox("setValue", rowData.forger);
		$("#roleId").combobox("setValue", rowData.roleId);
		$("#score").numberspinner("setValue", rowData.score);
		$("#categoryId").combobox("setValue", rowData.categoryId);
		$("#taozhuangId").combobox("setValue", rowData.taozhuangId);

		$("#qiling_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！", "warning");
	}
}

function attributeHandler() {
	let rowData = $("#qiling_list").datagrid("getSelected");

	if (rowData) {
		$("#property_list").datagrid("reload", {
			qilingId: rowData.id
		});

		$("#property_dialog").dialog("open");
	} else {
		unselected();
	}
}

function viewHandler() {
	let rowData = $("#qiling_list").datagrid("getSelected");

	if (rowData) {
		$("#attribute").hide();
		$("#qiling_attribute").empty();
		$("#taozhuang").hide();
		$("#qiling_taozhuang").html("");
		$("#qiling_xiaoguo").html("");

		ajaxGet("/qiling_category/selectById", {
			id: rowData.categoryId
		}, function(resp) {
			let data = resp.data;

			$("#qiling_image").attr("src", data.image);
			$("#qiling_name").html(data.name);
			$("#qiling_grade").html(data.grade);
			$("#qiling_note").html(data.note);

			if(rowData.taozhuangId !== 1) {
				ajaxGet("/qiling_taozhuang/selectById", {
					id: rowData.taozhuangId
				}, function(resp) {
					let data = resp.data;

					$("#taozhuang").show();
					$("#qiling_xiaoguo").html(data.note);
					$("#qiling_taozhuang").html(data.name);
				}, error);
			}
		}, error);

		ajaxGet("/qiling_attribute/selectAttributes", {
			qilingId: rowData.id
		}, function(resp) {
			let data = resp.data;

			if (data.length > 0) {
				let html = "";

				for (let i = 0; i < data.length; i++) {
					html += "&emsp;" + data[i].propertyName + "&ensp;+" + data[i].propertyValue + "<br/>";
				}

				$("#qiling_attribute").append(html);
				$("#attribute").show();
			}
		}, error);

		$("#qiling_forger").html(rowData.forger);
		$("#qiling_score").html(rowData.score);

		$("#qiling_detail").dialog("open");
	} else {
		unselected();
	}
}

function computeHandler() {
	let rowData = $("#qiling_list").datagrid("getSelected");

	if (rowData) {
		ajaxPost("/qiling/compute", {
			qilingId: rowData.id
		}, function(resp) {
			showMsg(resp.message);

			$("#qiling_list").datagrid("reload");
		}, error);
	} else {
		unselected();
	}
}

function deleteHandler() {
	let rowData = $("#qiling_list").datagrid("getSelected");

	if (rowData) {
		$.messager.confirm("提示", "是否确认删除？", function(bool) {
			if (bool) {
				ajaxPost("/qiling/deleteById", {
					id: rowData.id
				}, function(resp) {
					showMsg(resp.message);

					$("#qiling_list").datagrid("reload");
				}, error);
			}
		});
	} else {
		alertMsg("请选择要删除的记录！", "info");
	}
}

$(document).ready(function() {

	$("#categoryId").combobox({
		url: "/qiling_category/selectAll",
        valueField: "id",
        textField: "name",
        width: 150,
		required: true,
		panelHeight: "auto",
		formatter: function(row) {
			return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
		},
		onSelect: function (record) {
			$("#equipmentId").combogrid({
				categoryId: record.equipmentId
			});
		}
	});
	
	$("#forger").textbox({
		width: 150,
        required: true
    });
	
	$("#taozhuangId").combobox({
		url: "/qiling_taozhuang/selectAll",
        valueField: "id",
        textField: "name",
        width: 150,
		required: true,
		panelWidth: 180,
		panelHeight: "auto",
		formatter: function(row) {
			let text = "";
			
			text += "<table>";
			text += 	"<tr>"
			text += 		"<td>"
			text += 			"<img width='20' src='" + row.image + "' />&nbsp;";
			text += 		"</td>";
			text += 		"<td>";
			text += 			"<span style='font-size:18px;'>" + row.name + "</span>";
			text += 		"</td>";
			text += 	"</tr>";
			text += "</table>";
			
			return text;
		}
	});
	
	$("#score").numberspinner({
		min: 0,
		width: 150,
        required: true
	});

	$("#roleId").combobox({
		url: "/role_account/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto",
		formatter: function(row) {
			ajaxGet("/role_category/selectById", {
				id: row.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#_role_" + row.id).attr({
					"title": data.name,
					"src": data.image,
					"alt": data.name
				});
			}, error);

			return "<img height='20' id='_role_" + row.id + "' />&nbsp;" + row.name;
		}
	});
	
	$("#qiling_dialog").dialog({
		title: "器灵信息",
		width: 500,
		height: 300,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#qiling_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#qiling_dialog").dialog("close");
						$("#qiling_list").datagrid("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#qiling_form").form("clear");
				$("#qiling_dialog").dialog("close");
			}
		}]
	});

	/******************************************************************************************************/

	$("#property_list").datagrid({
		url: "/qiling_attribute/selectByQilingId",
		title: "器灵属性列表",
		fitColumns: true,
		method: "get",
		width: 480,
		height: 300,
		/**
		 * 结束行内编辑事件
		 * @param rowIndex 行号
		 * @param rowData 行数据
		 * @param changes 行更新数据
		 */
		onAfterEdit: function (rowIndex, rowData, changes) {
			data = {
				id: rowData.id,
				qilingId: rowData.qilingId,
				propertyId: changes.propertyId ? changes.propertyId : rowData.propertyId,
				propertyValue: changes.propertyValue ? changes.propertyValue : rowData.propertyValue
			};
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				let datagrid = $("#property_list");
				let rowData = $("#qiling_list").datagrid("getSelected");

				if(rowData) {
					requestUrl = "/qiling_attribute/insert";

					datagrid.datagrid("appendRow",{
						qilingId: rowData.id,
						propertyId: null,
						propertyValue: 1
					});

					let total = datagrid.datagrid("getRows").length;

					editingId = total - 1;

					datagrid.datagrid("beginEdit", editingId);
				} else {
					unselected("请选择一件器灵~");
				}
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				let datagrid = $("#property_list");

				if (editingId != null) {
					datagrid.datagrid("selectRow", editingId);
				} else {
					let row = datagrid.datagrid("getSelected");

					if (row) {
						// 获取行索引，这个索引从0开始
						let rowIndex = datagrid.datagrid("getRowIndex", row);

						editingId = rowIndex;
						requestUrl = "/qiling_attribute/updateById";

						datagrid.datagrid("beginEdit", rowIndex);
					}
				}
			}
		}, "-", {
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				if (editingId != null) {
					// 只有结束编辑才能获取到最新的值
					$("#property_list").datagrid("endEdit", editingId);

					ajaxPost(requestUrl, data, function(resp) {
						editingId = null;

						showMsg(resp.message);

						$("#property_list").datagrid("reload");
					}, error);
				}
			}
		}, "-", {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				if (editingId != null) {
					$("#property_list").datagrid("cancelEdit", editingId);

					editingId = null;
				}
			}
		}, "-", {
			iconCls: "icon-ok",
			text: "一键添加",
			handler: function() {
				let rowData = $("#qiling_list").datagrid("getSelected");

				if(rowData) {
					ajaxPost("/qiling_attribute/allocate", {
						qilingId: rowData.id
					}, function(resp) {
						showMsg(resp.message);

						$("#property_list").datagrid("reload");
					}, error);
				} else {
					unselected("请选择一件器灵~");
				}
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				let rowData = $("#property_list").datagrid("getSelected");

				if(rowData) {
					$.messager.confirm("提示", "是否确认删除？", function(bool) {
						if (bool) {
							ajaxPost("/qiling_attribute/deleteById", {
								id: rowData.id
							}, function(resp) {
								showMsg(resp.message);

								$("#property_list").datagrid("reload");
							}, error);
						}
					});
				} else {
					unselected();
				}
			}
		}],
		columns: [[
			{field: "id", hidden: true},
			{field: "qilingId", hidden: true},
			{field: "propertyId", title: "属性", align: "center", width: 150
				, editor: {
					type: "combobox",
					options: {
						url: "/qiling_view_attribute/selectProperty",
						valueField: "id",
						textField: "name",
						editable: true,
						panelHeight: "auto"
					}
				}
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/property/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							$("#property_" + rowIndex).html(data.name)
								.prop("title", data.name);
						}, error);

						return "<div class='blue' id='property_" + rowIndex + "'></div>";
					}
				}
			},
			{field: "propertyValue", title: "属性值", align: "center", width: 150
				, editor: {
					type: "numberspinner",
					options: {
						min: 1
					}
				}
			}
		]]
	});

	$("#property_dialog").dialog({
		title: " ",
		height: 340
	});

	/******************************************************************************************************/

	$("#qiling_detail .splitter").textbox({
		width: 205
	});

	// 器灵详情对话框
	$("#qiling_detail").dialog({
		title: " ",
		width: 225
	});

	/******************************************************************************************************/

	/**
	 * 表格体的高度
	 * @type {number}
	 */
	let heigt_body = heigt_tr_with_role_details * 10;
	/**
	 * 表格高度
	 * @type {number}
	 */
	let height_table = heigt_tool + heigt_header + heigt_filter + heigt_body + heigt_footer + heigt_scoll_bar + 2;

	let datagrid = $("#qiling_list").datagrid({
		url: "/qiling/selectByPage",
		height: height_table,
		fitColumns: true,
		rownumbers: true,
		pagination: true,
		remoteFilter: true,
		clientPaging: false,
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-shield",
			text: "属性",
			handler: function() {
				attributeHandler();
			}
		}, "-", {
			iconCls: "icon-search",
			text: "查看",
			handler: function() {
				viewHandler();
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				deleteHandler();
			}
		}, "-", {
			iconCls: "icon-ok",
			text: "计算评分",
			handler: function() {
				computeHandler();
			}
		}],
		columns: [[
			{field: "categoryId", title: "器灵类型", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/qiling_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#qiling_category_" + rowIndex).tooltip({
					        position: "left",
					        content: "<span class='white'>" + data.name + "：" + data.note + "</span>",
					        onShow: function() {
					    		$(this).tooltip("tip").css({
					    			backgroundColor: "#666",
					    			borderColor: "#666"
					    		});
					        }
					    }).attr("src", data.image);
					}, error);
					
					return "<img height='" + size + "' id='qiling_category_" + rowIndex + "' />";
				}
			},
			{field: "forger", title: "打造者", align: "center", width: 160},
			{field: "score", title: "评分", align: "center", width: 160, sortable: true},
			{field: "taozhuangId", title: "套装", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/qiling_taozhuang/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#taozhuang_" + rowIndex).tooltip({
							position: "left",
							content: "<span class='white'>" + data.name + "：" + data.note + "</span>",
							onShow: function() {
								$(this).tooltip("tip").css({
									backgroundColor: "#666",
									borderColor: "#666"
								});
							}
						}).html(data.name);
					}, error);

					return "<span class='blue' id='taozhuang_" + rowIndex + "'></span>";
				}
			},
			{field: "equipmentId", title: "镶嵌装备", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					if(value) {
						ajaxGet("/equipment/selectById", {
							id: value
						}, function(resp) {
							let equipment = resp.data;

							ajaxGet("/equipment_category/selectById", {
								id: equipment.categoryId
							}, function(resp) {
								let data = resp.data;

								$("#_equipment_" + rowIndex).attr({
									src: data.image,
									title: data.name
								});
							}, error);
						}, error);

						return "<img height='" + size + "' id='_equipment_" + rowIndex + "' />";
					}

					return "/";
				}
			},
			roleDetailsColumn
		]]
	});

	datagrid.datagrid("enableFilter", [{
		field: "score",
		type: "numberspinner",
		operator: ["equal", "less", "lessorequal", "greater", "greaterorequal"],
		options: {
			min: 0
		}
	}, {
		field: "forger",
		type: "textbox",
		operator: ["equal", "notequal", "contains"]
	}, {
		field: "roleId",
		type: "combobox",
		options: {
			url: "/role_account/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			formatter: function(row) {
				ajaxGet("/role_category/selectById", {
					id: row.categoryId
				}, function(resp) {
					let data = resp.data;

					$("#role_" + row.id).attr({
						"title": data.name,
						"src": data.image,
						"alt": data.name
					});
				}, error);

				return "<img width='20' id='role_" + row.id + "' />&nbsp;" + row.name;
			}
		},
		operator: ["equal", "notequal"]
	}, {
		field: "categoryId",
		type: "combobox",
		options: {
			url: "/qiling_category/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			formatter: function(row) {
				return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
			}
		},
		operator: ["equal", "notequal"]
	}, {
		field: "taozhuangId",
		type: "combobox",
		options: {
			url: "/qiling_taozhuang/selectAll",
			valueField: "id",
			textField: "name",
			panelHeight: "auto",
			formatter: function(row) {
				let text = "";

				text += "<table>";
				text += 	"<tr>"
				text += 		"<td>"
				text += 			"<img width='20' src='" + row.image + "' />&nbsp;";
				text += 		"</td>";
				text += 		"<td>";
				text += 			"<span style='font-size:18px;'>" + row.name + "</span>";
				text += 		"</td>";
				text += 	"</tr>";
				text += "</table>";

				return text;
			}
		},
		operator: ["equal", "notequal"]
	}]);

});